package api

import (
	"family/api/dto"
	"family/dao"
	"family/model"
	"family/pkg/constant"
	"family/pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"time"
)

var EventAPI = new(eventAPI)

type eventAPI struct{}

func (*eventAPI) Create(c *gin.Context) {
	var addDTO dto.EventAddDTO
	if err := c.ShouldBindJSON(&addDTO); err != nil {
		response.ERROR(c, response.Validate, err.Error())
		return
	}
	eventTime, err := time.Parse(constant.DATE, addDTO.EventTime)
	if err != nil {
		response.ERROR(c, response.UNIVERSAL, err.Error())
	}
	err = dao.EventDao.Create(&model.Event{
		People:    cast.ToUint64(addDTO.People),
		Title:     addDTO.Title,
		EventTime: eventTime,
		Content:   addDTO.Content,
	})
	if err != nil {
		response.ERROR(c, response.UNIVERSAL, err.Error())
		return
	}
	response.OK(c, nil)
}

func (*eventAPI) Details(c *gin.Context) {
	param := c.Param("ID")
	info, err := dao.EventDao.Info(param)
	if err != nil {
		response.ERROR(c, response.UNIVERSAL, err.Error())
		return
	}
	eventDTO := dto.EventDTO{
		ID:        cast.ToString(info.ID),
		People:    cast.ToString(info.People),
		Title:     info.Title,
		EventTime: info.EventTime.Format(constant.DATE),
		Content:   info.Content,
	}

	response.OK(c, eventDTO)
}

func (*eventAPI) Page(c *gin.Context) {

	People := cast.ToUint64(c.Query("People"))
	events, i, err := dao.EventDao.Page(People)
	if err != nil {
		return
	}
	var eventDTOS []*dto.EventDTO

	for _, event := range events {
		eventDTO := &dto.EventDTO{
			ID:        cast.ToString(event.ID),
			People:    cast.ToString(event.People),
			Title:     event.Title,
			EventTime: event.EventTime.Format(constant.DATE),
			Content:   event.Content,
		}
		eventDTOS = append(eventDTOS, eventDTO)
	}
	response.Page(c, i, eventDTOS)

}

func (*eventAPI) Update(c *gin.Context) {
	var updateDTO dto.EventUpdateDTO
	if err := c.ShouldBindJSON(&updateDTO); err != nil {
		response.ERROR(c, response.Validate, err.Error())
		return
	}
	eventTime, err := time.Parse(constant.DATE, updateDTO.EventTime)
	if err != nil {
		response.ERROR(c, response.UNIVERSAL, err.Error())
	}
	err = dao.EventDao.Update(&model.Event{
		ID:        cast.ToUint64(updateDTO.ID),
		People:    cast.ToUint64(updateDTO.People),
		Title:     updateDTO.Title,
		EventTime: eventTime,
		Content:   updateDTO.Content,
	})
	if err != nil {
		response.ERROR(c, response.UNIVERSAL, err.Error())
		return
	}
	response.OK(c, nil)
}

func (*eventAPI) Delete(c *gin.Context) {
	var deleteDTO dto.EventDeleteDTO
	if err := c.ShouldBindJSON(&deleteDTO); err != nil {
		response.ERROR(c, response.Validate, err.Error())
		return
	}
	err := dao.EventDao.Delete(deleteDTO.Ids)
	if err != nil {
		response.ERROR(c, response.UNIVERSAL, err.Error())
		return
	}
	response.OK(c, nil)
}
